﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Bule.Malbilden.Configuration
{
    public class XmlConfigurationReader : IConfigurationReader
    {
        private XDocument config;

        public XmlConfigurationReader(XDocument configuration)
        {
            this.config = configuration;
        }

        public XmlConfigurationReader(string path)
        {
            config = XDocument.Load(path);
        }

        /// <summary>
        /// Reads all children of the base node.
        /// </summary>
        /// <remarks>Assumes a one level xml document (only root element with children, no childrens children).</remarks>
        /// <returns>A dictionary with the child name as key and the child value as value.</returns>
        public IDictionary<string, string> GetConfigurationDictionary()
        {
            var dictionary = new Dictionary<string, string>();

            var decendants = config.Root.Descendants();

            foreach (var node in decendants)
                dictionary.Add(node.Name.ToString(), node.Value);

            return dictionary;
        }

        /// <summary>
        /// Reads all children of the node with the specified category name.
        /// </summary>
        /// <remarks>Assumes that the specified node (with the name categoryName) only has one level of children.</remarks>
        /// <returns>A dictionary with the child name as key and the child value as value.</returns>
        public IDictionary<string, string> GetConfigurationDictionary(string categoryName)
        {
            var dictionary = new Dictionary<string, string>();

            var decendants = config.Descendants(categoryName).Descendants();

            foreach (var node in decendants)
                dictionary.Add(node.Name.ToString(), node.Value);

            return dictionary;
        }
    }
}
